<template>
  <a-modal
    :title="title"
    :width="900"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <template slot="footer">
      <a-button key="close" @click="handleCancel">关闭</a-button>
    </template>

    <a-spin :spinning="confirmLoading">
      <a-card :bordered="false">
        <!-- 交易记录汇总 -->
        <div class="transaction-summary">
          <a-row :gutter="16">
            <a-col :span="8">
              <a-statistic
                title="销售总额"
                :value="orderInfo.totalAmount || 0"
                :precision="2"
                prefix="¥"
                :valueStyle="{ color: '#3f8600' }"
              />
            </a-col>
            <a-col :span="8">
              <a-statistic
                title="已付款"
                :value="orderInfo.paidAmount || 0"
                :precision="2"
                prefix="¥"
                :valueStyle="{ color: '#1890ff' }"
              />
            </a-col>
            <a-col :span="8">
              <a-statistic
                title="待付款"
                :value="orderInfo.unpaidAmount || 0"
                :precision="2"
                prefix="¥"
                :valueStyle="orderInfo.unpaidAmount > 0 ? { color: '#cf1322' } : { color: '#52c41a' }"
              />
            </a-col>
          </a-row>
        </div>
        
        <!-- 交易记录列表 -->
        <a-table
          :columns="columns"
          :dataSource="transactionList"
          :pagination="ipagination"
          :loading="tableLoading"
          :rowKey="record => record.id"
          @change="handleTableChange"
        >
          <!-- 交易类型 -->
          <template slot="transactionTypeSlot" slot-scope="text">
            <j-dict-tag :value="text" dictCode="transaction_type" />
          </template>
          
          <!-- 支付方式 -->
          <template slot="paymentMethodSlot" slot-scope="text">
            <j-dict-tag :value="text" dictCode="payment_method" />
          </template>
          
          <!-- 金额 -->
          <template slot="amountSlot" slot-scope="text">
            <span :style="{ color: Number(text) < 0 ? '#f5222d' : '#52c41a', fontWeight: 'bold' }">
              {{ Number(text).toLocaleString('zh-CN', { style: 'currency', currency: 'CNY' }) }}
            </span>
          </template>
          
          <!-- 凭证 -->
          <template slot="paymentVoucherSlot" slot-scope="text">
            <div v-if="text && isImageFile(text)" class="voucher-thumbnail-container" @click="previewVoucher(text)">
              <img
                :src="getFullImageUrl(text)"
                class="voucher-thumbnail"
                alt="凭证缩略图"
                @error="handleImageError"
              />
            </div>
            <a v-else-if="text" @click="previewVoucher(text)" class="voucher-link">查看凭证</a>
            <span v-else>无</span>
          </template>
          
          <!-- 描述信息 -->
          <template slot="descriptionSlot" slot-scope="text">
            <a-tooltip :title="text" placement="topLeft" v-if="text && text.length > 30">
              <span>{{ text.slice(0, 30) }}...</span>
            </a-tooltip>
            <span v-else-if="text">{{ text }}</span>
            <span v-else class="empty-description">暂无描述信息</span>
          </template>
        </a-table>
        
        <!-- 空数据提示 -->
        <div v-if="!transactionList || transactionList.length === 0" class="empty-data">
          <a-empty description="暂无交易记录" />
        </div>
      </a-card>
    </a-spin>
    
    <!-- 凭证预览模态框 -->
    <a-modal
      title="凭证预览"
      :visible="voucherPreviewVisible"
      @cancel="closeVoucherPreview"
      :footer="null"
      :width="800"
      :destroyOnClose="true"
    >
      <div class="voucher-preview-container">
        <!-- 图片文件直接显示 -->
        <img
          v-if="isImageFile(currentVoucherUrl)"
          :src="currentVoucherUrl"
          class="voucher-preview-image"
          @error="handleImageError"
        />
        <!-- 非图片文件使用iframe嵌入显示 -->
        <iframe
          v-else
          :src="getPreviewUrl(currentVoucherUrl)"
          class="voucher-preview-iframe"
          frameborder="0"
          allowfullscreen
        ></iframe>
      </div>
    </a-modal>
  </a-modal>
</template>

<script>
import { getAction } from '@/api/manage'
import moment from 'moment'
import { getFileAccessHttpUrl } from '@/api/manage'

export default {
  name: 'ProductOrderTransaction',
  data() {
    return {
      title: '交易记录',
      visible: false,
      confirmLoading: false,
      tableLoading: false,
      orderId: '',
      orderInfo: {}, // 订单基本信息
      transactionList: [], // 交易记录列表
      ipagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showTotal: (total) => `共 ${total} 条`
      },
      // 凭证预览相关
      voucherPreviewVisible: false,
      currentVoucherUrl: '',
      
      // 表格列定义
      columns: [
        {
          title: '交易时间',
          dataIndex: 'transactionTime',
          sorter: true,
          customRender: (text) => {
            return text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : ''
          }
        },
        {
          title: '交易类型',
          dataIndex: 'transactionType',
          scopedSlots: { customRender: 'transactionTypeSlot' }
        },
        {
          title: '支付方式',
          dataIndex: 'paymentMethod',
          scopedSlots: { customRender: 'paymentMethodSlot' }
        },
        {
          title: '金额',
          dataIndex: 'amount',
          sorter: true,
          scopedSlots: { customRender: 'amountSlot' }
        },
        {
          title: '交易人员',
          dataIndex: 'transactionPersonName',
        },
        {
          title: '凭证',
          dataIndex: 'paymentVoucher',
          scopedSlots: { customRender: 'paymentVoucherSlot' }
        },
        {
          title: '描述',
          dataIndex: 'description',
          scopedSlots: { customRender: 'descriptionSlot' }
        }
      ],
      url: {
        getOrderById: '/oms/productSalesOrder/queryById',
        pageByOrderId: '/oms/productSalesOrder/transaction/pageByOrderId'
      }
    }
  },
  methods: {
    show(id) {
      this.visible = true
      this.orderId = id
      this.loadOrderInfo()
      this.loadData()
    },
    
    // 加载订单基本信息
    loadOrderInfo() {
      this.confirmLoading = true
      getAction(this.url.getOrderById, { id: this.orderId }).then(res => {
        if (res.success && res.result) {
          this.orderInfo = res.result
          
          // 确保金额字段有值
          if (this.orderInfo.totalAmount === undefined || this.orderInfo.totalAmount === null) {
            this.orderInfo.totalAmount = 0
          }
          
          if (this.orderInfo.paidAmount === undefined || this.orderInfo.paidAmount === null) {
            this.orderInfo.paidAmount = 0
          }
          
          if (this.orderInfo.unpaidAmount === undefined || this.orderInfo.unpaidAmount === null) {
            this.orderInfo.unpaidAmount = this.orderInfo.totalAmount - this.orderInfo.paidAmount
          }
        } else {
          this.$message.warning('获取订单信息失败')
        }
        this.confirmLoading = false
      }).catch(err => {
        console.error('获取订单信息异常:', err)
        this.$message.error('获取订单信息失败')
        this.confirmLoading = false
      })
    },
    
    // 加载交易记录数据
    loadData() {
      this.tableLoading = true
      let params = {
        orderId: this.orderId,
        pageNo: this.ipagination.current,
        pageSize: this.ipagination.pageSize,
        sortField: 'transactionTime',
        sortOrder: 'desc'
      }
      
      getAction(this.url.pageByOrderId, params).then(res => {
        if (res.success) {
          this.transactionList = res.result.records || []
          this.ipagination.total = res.result.total || 0
        } else {
          this.$message.warning(res.message || '获取交易记录失败')
          this.transactionList = []
        }
        this.tableLoading = false
      }).catch(err => {
        console.error('获取交易记录异常:', err)
        this.$message.error('获取交易记录失败')
        this.transactionList = []
        this.tableLoading = false
      })
    },
    
    // 表格变化处理
    handleTableChange(pagination, filters, sorter) {
      this.ipagination.current = pagination.current
      this.ipagination.pageSize = pagination.pageSize
      
      // 处理排序
      if (sorter && sorter.field) {
        this.loadData({
          sortField: sorter.field,
          sortOrder: sorter.order === 'descend' ? 'desc' : 'asc'
        })
      } else {
        this.loadData()
      }
    },
    
    // 检查是否为图片文件
    isImageFile(url) {
      if (!url) return false
      return /\.(jpg|jpeg|png|gif|bmp)$/i.test(url)
    },
    
    // 预览凭证
    previewVoucher(url) {
      if (!url) {
        this.$message.warning('无凭证可预览')
        return
      }
      
      // 获取完整的凭证URL
      this.currentVoucherUrl = this.getFullImageUrl(url)
      
      if (!this.isImageFile(url)) {
        // 非图片文件，使用新窗口打开
        window.open(this.getPreviewUrl(url), '_blank')
        return
      }
      
      // 显示预览模态框
      this.voucherPreviewVisible = true
    },
    
    // 关闭凭证预览
    closeVoucherPreview() {
      this.voucherPreviewVisible = false
      this.currentVoucherUrl = ''
    },
    
    // 获取完整图片URL
    getFullImageUrl(url) {
      if (!url) return ''
      
      try {
        return getFileAccessHttpUrl(url)
      } catch (error) {
        console.error('获取文件URL失败:', error)
        return ''
      }
    },
    
    // 获取预览URL
    getPreviewUrl(url) {
      if (!url) return ''
      
      // 获取完整URL
      const fullUrl = this.getFullImageUrl(url)
      
      // 使用kkfileview预览非图片文件
      const previewBaseUrl = process.env.VUE_APP_ONLINE_BASE_URL || 'http://fileview.jeecg.com/onlinePreview'
      
      return `${previewBaseUrl}?url=${encodeURIComponent(fullUrl)}`
    },
    
    // 处理图片加载错误
    handleImageError(e) {
      e.target.style.display = 'none'
      const container = e.target.parentNode
      if (container) {
        const icon = document.createElement('i')
        icon.className = 'anticon anticon-picture'
        icon.style.fontSize = '24px'
        icon.style.color = '#d9d9d9'
        container.insertBefore(icon, e.target)
        
        const errorText = document.createElement('div')
        errorText.innerText = '图片不存在'
        errorText.style.color = '#ff4d4f'
        errorText.style.fontSize = '12px'
        errorText.style.marginTop = '4px'
        container.appendChild(errorText)
      }
    },
    
    // 关闭模态框
    handleCancel() {
      this.visible = false
      this.transactionList = []
      this.orderId = ''
      this.orderInfo = {}
      this.ipagination.current = 1
    }
  }
}
</script>

<style lang="less" scoped>
.transaction-summary {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.voucher-thumbnail-container {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border: 1px solid #e8e8e8;
  background-color: #f5f5f5;
  
  &:hover {
    border-color: #1890ff;
    box-shadow: 0 0 8px rgba(24, 144, 255, 0.2);
  }
}

.voucher-thumbnail {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.voucher-link {
  color: #1890ff;
}

.empty-description {
  color: rgba(0, 0, 0, 0.45);
  font-style: italic;
}

.empty-data {
  padding: 32px 0;
  text-align: center;
}

.voucher-preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
  max-height: 600px;
  overflow: auto;
}

.voucher-preview-image {
  max-width: 100%;
  max-height: 500px;
}

.voucher-preview-iframe {
  width: 100%;
  height: 500px;
  border: none;
}
</style> 